import { sendQuestionService } from '@/api/chat';
import { defineStore } from 'pinia';
import { v4 as uuidv4 } from 'uuid';

// 定义消息类型
export interface Message {
  id: string;
  content: string;
  reasoning_content?: string;
  role: 'user' | 'assistant';
  timestamp: number;
  isStreaming: boolean;
}

// 定义会话类型
export interface ChatSession {
  id: string;
  title: string;
  createdAt: number;
  updatedAt: number;
  messages: Message[];
  isSelected?: boolean;
}

interface ChatState {
  sessions: ChatSession[];
  currentSessionId: string | null;
  currentMessages: Message[];
  abortController: AbortController | null;
  currentStreamContent: string;
}

export const useChatStore = defineStore('chat', {
  state: (): ChatState => ({
    sessions: [],
    currentSessionId: null,
    currentMessages: [],
    abortController: null,
    currentStreamContent: '',
  }),

  actions: {
    // 创建新会话
    createNewSession() {
      const newSession: ChatSession = {
        id: uuidv4(),
        title: '新对话',
        createdAt: Date.now(),
        updatedAt: Date.now(),
        messages: [],
        isSelected: true,
      };

      // 取消其他会话的选中状态
      this.sessions.forEach((s) => (s.isSelected = false));

      this.sessions.unshift(newSession);
      this.currentSessionId = newSession.id;
    },

    // 删除会话
    deleteSession(sessionId: string) {
      this.sessions = this.sessions.filter((s) => s.id !== sessionId);
      if (this.currentSessionId === sessionId) {
        this.currentSessionId = this.sessions[0]?.id || null;
      }
    },

    // 切换当前会话
    switchSession(sessionId: string) {
      this.sessions.forEach((s) => {
        s.isSelected = s.id === sessionId;
      });
      this.currentSessionId = sessionId;
    },
    // 中止请求
    abortStreaming() {
      if (this.abortController) {
        this.abortController.abort();
        this.abortController = null;
        this.finalizeStreaming();
      }
    },
    // 结束流式传输
    finalizeStreaming() {
      const session = this.currentSession;
      if (!session) return;

      const lastMessage = session.messages[session.messages.length - 1];
      if (lastMessage) {
        lastMessage.isStreaming = false;
      }
      this.abortController = null;
    },
    // 添加消息到当前会话
    addMessage(message: Omit<Message, 'id' | 'timestamp'>) {
      if (!this.currentSessionId) {
        this.createNewSession();
      }

      const session = this.sessions.find((s) => s.id === this.currentSessionId);
      if (session) {
        const newMessage: Message = {
          id: uuidv4(),
          ...message,
          timestamp: Date.now(),
        };
        session.messages.push(newMessage);
        session.updatedAt = Date.now();

        // 自动生成标题（当第一个用户消息时）
        if (session.messages.length === 1 && message.role === 'user') {
          session.title = message.content.substring(0, 20);
        }
        // 消息列表添加用户问题
        // this.currentMessages.push(newMessage);

        // 消息列表加
        const assistantMessage: Message = {
          id: uuidv4(),
          content: '正在思考中...',
          reasoning_content: '',
          role: 'assistant',
          timestamp: Date.now(),
          isStreaming: true,
        };
        this.abortController = new AbortController();
        this.currentStreamContent = '';
        sendQuestionService(session.messages, (data) => {
          try {
            if ('[DONE]' === data) {
              this.finalizeStreaming();
              return;
            }
            const part: any = JSON.parse(data);

            const lastMessage = session.messages[session.messages.length - 1];
            // lastMessage.id = part.id;
            // assistantMessage.id = part.id;
            if (lastMessage.content === '正在思考中...') {
              lastMessage.content = '';
            }
            let newContent = part.choices[0].delta.reasoning_content as string;
            if (typeof part.choices[0].delta.reasoning_content === 'string') {
              this.updateAssistantMessage(newContent, 'reasoning_content');
            } else if (typeof part.choices[0].delta.content === 'string') {
              newContent = part.choices[0].delta.content as string;
              this.updateAssistantMessage(newContent, 'content');
            }
          } catch (error) {
            console.error('Error parsing chunk:', error);
          }
        });
        // this.currentMessages.push(assistantMessage);
        session.messages.push(assistantMessage);
      }
    },

    // 更新AI回答内容（用于流式输出）
    updateAssistantMessage(content: string, type?: 'reasoning_content' | 'content') {
      const session = this.sessions.find((s) => s.id === this.currentSessionId);
      if (session) {
        const lastMessage = session.messages[session.messages.length - 1];
        if (
          lastMessage.role === 'assistant' &&
          typeof content === 'string' &&
          ['null', 'undefined'].indexOf(content) === -1
        ) {
          this.currentStreamContent += content || '';
          if (type === 'reasoning_content') {
            lastMessage.reasoning_content += content || '';
          } else if (type === 'content') {
            lastMessage.content += content;
          }
        }
      }
    },
  },

  getters: {
    currentSession: (state): ChatSession | undefined => {
      return state.sessions.find((s) => s.id === state.currentSessionId);
    },
    sortedSessions: (state) => {
      return [...state.sessions].sort((a, b) => b.updatedAt - a.updatedAt);
    },
    lastMessage: (state) => {
      const session = state.sessions.find((s) => s.id === state.currentSessionId);
      if (session && session.messages.length > 0) {
        return session.messages[session.messages.length - 1];
      }
      return null;
    },
  },
});
